<template>
  <div v-if="!settingsStore.isMobile" class="chatbot-container">
    <!-- 悬浮按钮 -->
    <FloatingButton
      v-show="!isChatOpen"
      :icon="aiRobotImg"
      alt="AI Robot"
      @click="openChat"
    />

    <!-- 聊天窗口 -->
    <transition name="chat-fade">
      <div
        v-show="isChatOpen"
        class="chat-window"
        :class="{ 'is-dragging': isDraggingChat }"
        :style="{ left: chatPosition.x + 'px', top: chatPosition.y + 'px' }"
      >
        <!-- 标题栏 -->
        <div class="chat-header" @mousedown="startDragChat">
          <div class="header-left">
            <img :src="aiRobotImg" alt="AI Robot" class="header-icon" />
            <span class="header-title">AI智能助手-铁蛋</span>
          </div>
          <div class="header-right">
            <el-icon class="minimize-btn" @click="minimizeChat">
              <Minus />
            </el-icon>
            <el-icon class="close-btn" @click="closeChat">
              <Close />
            </el-icon>
          </div>
        </div>

        <!-- 消息区域 - 使用 el-scrollbar -->
        <el-scrollbar ref="scrollbarRef" class="chat-messages">
          <div ref="messagesContainer" class="messages-wrapper">
            <div
              v-for="(msg, index) in messages"
              :key="index"
              :class="['message-item', msg.role]"
            >
              <!-- 头像 -->
              <el-avatar
                v-if="msg.role === 'assistant'"
                :size="36"
                :src="aiRobotImg"
                class="message-avatar ai-avatar"
              />
              <el-avatar
                v-else
                :size="36"
                :icon="UserFilled"
                :src="webInfoStore.currentWebUserAvatar"
                class="message-avatar user-avatar-img"
              />

              <!-- 消息内容 -->
              <div class="message-content">
                <el-card
                  shadow="hover"
                  :body-style="{ padding: '8px 12px' }"
                  :class="['message-card', msg.role]"
                >
                  <div class="message-text" v-html="formatMessage(msg.content)"></div>
                </el-card>
                <div class="message-time">{{ msg.time }}</div>
              </div>
            </div>

            <!-- 加载动画 -->
            <div v-if="isLoading" class="message-item assistant">
              <el-avatar :size="36" :src="aiRobotImg" class="message-avatar ai-avatar" />
              <div class="message-content">
                <el-card shadow="hover" :body-style="{ padding: '8px 12px' }" class="message-card assistant">
                  <TypingIndicator />
                </el-card>
              </div>
            </div>
          </div>
        </el-scrollbar>

        <!-- 输入区域 -->
        <el-divider style="margin: 0" />
        <div class="chat-input">
          <el-input
            v-model="userInput"
            type="textarea"
            :rows="2"
            placeholder="请输入您的问题..."
            @keydown.enter.prevent="handleEnter"
            :disabled="isLoading"
            resize="none"
          />
          <el-space :size="10" style="width: 100%; justify-content: flex-end">
            <el-button
              type="primary"
              :icon="Promotion"
              @click="sendMessage"
              :loading="isLoading"
              :disabled="!userInput.trim()"
            >
              发送
            </el-button>
          </el-space>
        </div>
      </div>
    </transition>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick, onMounted, onUnmounted } from "vue"
import { Close, Minus, User, Promotion, UserFilled } from "@element-plus/icons-vue"
import { ElMessage, ElNotification } from "element-plus"
import { chatWithAI } from "@/api/web/ai"
import { useWebInfoStore } from "@/store/modules/webInfo"
import { useSettingsStore } from "@/store/modules/settings"
import aiRobotImg from "@/assets/ai.png"
import { parseMarkdownToHtml } from "@/utils/markdown"
import TypingIndicator from "@/components/TypingIndicator/index.vue"
import FloatingButton from "@/components/FloatingButton/index.vue"

// 获取 store
const webInfoStore = useWebInfoStore()
const settingsStore = useSettingsStore()

// 组件状态
const isChatOpen = ref(false)
const isLoading = ref(false)
const userInput = ref("")
const messagesContainer = ref<HTMLElement>()
const scrollbarRef = ref()

// 消息列表
interface Message {
  role: "user" | "assistant"
  content: string
  time: string
}

// 初始化欢迎消息
const initWelcomeMessage = () => {
  const greeting = "你好！我是AI智能助手-铁蛋，有什么可以帮助你的吗？"

  return {
    role: "assistant" as const,
    content: greeting,
    time: getCurrentTime()
  }
}

const messages = ref<Message[]>([initWelcomeMessage()])

// 聊天窗口位置
const chatPosition = reactive({
  x: window.innerWidth - 420,
  y: window.innerHeight - 620
})

// 拖拽相关（仅聊天窗口）
let isDragging = false
let offsetX = 0
let offsetY = 0
const isDraggingChat = ref(false)

// 获取当前时间
function getCurrentTime(): string {
  const now = new Date()
  return `${now.getHours().toString().padStart(2, "0")}:${now.getMinutes().toString().padStart(2, "0")}`
}

// 格式化消息（前端实时渲染 Markdown）
function formatMessage(text: string): string {
  return parseMarkdownToHtml(text)
}

// 打开聊天窗口
function openChat() {
  isChatOpen.value = true
  // 调整窗口位置，避免超出屏幕
  adjustChatPosition()
}

// 最小化聊天窗口
function minimizeChat() {
  isChatOpen.value = false
}

// 关闭聊天窗口
function closeChat() {
  isChatOpen.value = false
}

// 调整聊天窗口位置
function adjustChatPosition() {
  const windowWidth = window.innerWidth
  const windowHeight = window.innerHeight
  const chatWidth = 800
  const chatHeight = 600

  // 确保窗口在屏幕内
  if (chatPosition.x + chatWidth > windowWidth) {
    chatPosition.x = windowWidth - chatWidth - 20
  }
  if (chatPosition.x < 20) {
    chatPosition.x = 20
  }
  if (chatPosition.y + chatHeight > windowHeight) {
    chatPosition.y = windowHeight - chatHeight - 20
  }
  if (chatPosition.y < 20) {
    chatPosition.y = 20
  }
}

// 开始拖拽聊天窗口
function startDragChat(e: MouseEvent) {
  offsetX = e.clientX - chatPosition.x
  offsetY = e.clientY - chatPosition.y
  isDraggingChat.value = false
  isDragging = false

  document.addEventListener("mousemove", handleDragChat)
  document.addEventListener("mouseup", stopDragChat)
}

// 处理拖拽聊天窗口
function handleDragChat(e: MouseEvent) {
  isDragging = true
  isDraggingChat.value = true

  const newX = e.clientX - offsetX
  const newY = e.clientY - offsetY

  chatPosition.x = Math.max(0, Math.min(newX, window.innerWidth - 800))
  chatPosition.y = Math.max(0, Math.min(newY, window.innerHeight - 600))
}

// 停止拖拽聊天窗口
function stopDragChat() {
  document.removeEventListener("mousemove", handleDragChat)
  document.removeEventListener("mouseup", stopDragChat)

  setTimeout(() => {
    isDragging = false
    isDraggingChat.value = false
  }, 100)
}

// 滚动到底部
function scrollToBottom() {
  nextTick(() => {
    if (scrollbarRef.value) {
      // 使用 el-scrollbar 的方法
      scrollbarRef.value.setScrollTop(messagesContainer.value?.scrollHeight || 9999)
    }
  })
}

// 处理回车键
function handleEnter(e: Event | KeyboardEvent) {
  const event = e as KeyboardEvent
  if (!event.shiftKey) {
    // 单独按回车发送
    sendMessage()
  }
  // Shift+回车换行，由textarea自己处理
}

// 发送消息
async function sendMessage() {
  if (!userInput.value.trim() || isLoading.value) return

  const message = userInput.value.trim()
  userInput.value = ""

  // 添加用户消息
  messages.value.push({
    role: "user",
    content: message,
    time: getCurrentTime()
  })

  scrollToBottom()
  isLoading.value = true

  try {
    // 调用AI接口
    const response = await chatWithAI({
      message: message,
      stream: false
    })

    // 添加AI回复
    messages.value.push({
      role: "assistant",
      content: response.reply || "抱歉，我现在无法回答。",
      time: getCurrentTime()
    })
  } catch (error: any) {
    console.error("AI对话失败:", error)
    ElMessage.error(error.message || "AI对话失败，请稍后重试")

    // 添加错误消息
    messages.value.push({
      role: "assistant",
      content: "抱歉，我遇到了一些问题，请稍后再试。",
      time: getCurrentTime()
    })
  } finally {
    isLoading.value = false
    scrollToBottom()
  }
}

// 监听窗口大小变化
function handleResize() {
  // 确保聊天窗口在可见范围内
  chatPosition.x = Math.min(chatPosition.x, window.innerWidth - 800)
  chatPosition.y = Math.min(chatPosition.y, window.innerHeight - 600)
}

onMounted(() => {
  window.addEventListener("resize", handleResize)

  // 显示欢迎提示
  ElNotification({
    title: "AI智能助手-铁蛋",
    message: "小小机器人已上线，快来体验吧~",
    type: "success",
    duration: 3000,
    position: "bottom-right",
    offset: 90,
    showClose: true
  })
})

onUnmounted(() => {
  window.removeEventListener("resize", handleResize)
  document.removeEventListener("mousemove", handleDragChat)
  document.removeEventListener("mouseup", stopDragChat)
})
</script>

<style scoped lang="scss">
// 聊天窗口
.chat-window {
  position: fixed;
  width: 800px;
  height: 600px;
  background: var(--el-bg-color);
  border-radius: 12px;
  box-shadow: var(--el-box-shadow);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  z-index: 9999;
  font-size: 14px;

  &.is-dragging {
    transition: none;
    cursor: move;
  }
}

// 标题栏
.chat-header {
  height: 50px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 12px;
  cursor: move;
  user-select: none;

  .header-left {
    display: flex;
    align-items: center;
    gap: 10px;

    .header-icon {
      width: 28px;
      height: 28px;
      object-fit: contain;
    }

    .header-title {
      font-size: 16px;
      font-weight: 600;
    }
  }

  .header-right {
    display: flex;
    gap: 12px;

    .minimize-btn,
    .close-btn {
      cursor: pointer;
      font-size: 18px;
      transition: transform 0.2s;

      &:hover {
        transform: scale(1.2);
      }
    }
  }
}

// 消息区域
.chat-messages {
  flex: 1;
  background: var(--el-bg-color-page);

  .messages-wrapper {
    padding: 12px;
  }
}

// 消息项
.message-item {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  margin-bottom: 16px;
  animation: fadeIn 0.3s ease;
  width: 100%;

  &.user {
    flex-direction: row-reverse;

    .message-content {
      align-items: flex-end;

      .message-time {
        text-align: right;
      }
    }

    .message-card {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      border: none;

      .message-text {
        color: #ffffff;

        pre {
          background: rgba(0, 0, 0, 0.3) !important;

          code {
            color: #ffffff !important;
          }
        }

        code.inline-code {
          background: rgba(255, 255, 255, 0.2);
          color: #ffffff;
        }

        a {
          color: #ffffff;
          text-decoration: underline;
        }

        p {
          margin: 0;
          color: #ffffff;
        }
      }
    }
  }

  .message-avatar {
    flex-shrink: 0;

    &.ai-avatar {
      background: transparent;
    }
  }

  .user-avatar-img {
    border: 2px solid var(--el-border-color);
    box-shadow: var(--el-box-shadow-light);
  }

  .message-content {
    display: flex;
    flex-direction: column;
    max-width: 75%;
    min-width: 0;
    flex: 1;

    .message-card {
      border-radius: 12px;
      width: 100%;

      :deep(.el-card__body) {
        padding: 8px 12px;
        overflow: visible;
      }

      .message-text {
        font-size: 14px;
        line-height: 1.6;
        word-break: break-word;
        max-width: 100%;
        overflow: visible;
        color: var(--el-text-color-primary);

        // 代码块
        pre {
          margin: 10px 0;
          padding: 12px;
          background: #282c34;
          border-radius: 6px;
          overflow-x: auto;
          max-width: 100%;
          white-space: pre;

          code {
            font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
            font-size: 13px;
            line-height: 1.5;
            color: #abb2bf;
            display: block;
          }
        }

        // 行内代码
        code.inline-code {
          padding: 2px 6px;
          background: var(--el-fill-color-light);
          border-radius: 3px;
          font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
          font-size: 13px;
          color: #e83e8c;
        }

        // 链接
        a {
          color: var(--el-color-primary);
          text-decoration: none;

          &:hover {
            text-decoration: underline;
          }
        }

        // 列表
        ul,
        ol {
          margin: 10px 0;
          padding-left: 20px;
        }

        li {
          margin: 5px 0;
        }

        // 段落
        p {
          margin: 5px 0;

          &:first-child {
            margin-top: 0;
          }

          &:last-child {
            margin-bottom: 0;
          }
        }

        // 标题
        h1,
        h2,
        h3 {
          margin: 10px 0;
          font-weight: 600;
          color: var(--el-text-color-primary);
        }

        h1 {
          font-size: 18px;
        }
        h2 {
          font-size: 16px;
        }
        h3 {
          font-size: 15px;
        }

        // 粗体、斜体
        strong {
          font-weight: 600;
        }

        em {
          font-style: italic;
        }

        // 换行
        br {
          display: block;
          content: "";
          margin: 5px 0;
        }
      }
    }

    .message-time {
      font-size: 12px;
      color: var(--el-text-color-secondary);
      margin-top: 4px;
      padding: 0 4px;
    }
  }
}

// 输入区域
.chat-input {
  padding: 12px;
  background: var(--el-bg-color);
  display: flex;
  flex-direction: column;
  gap: 8px;

  :deep(.el-textarea__inner) {
    box-shadow: none;
    font-size: 14px;

    &:focus {
      border-color: #667eea;
    }
  }

  :deep(.el-button--primary) {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border: none;
    font-size: 14px;

    &:hover {
      opacity: 0.9;
    }
  }
}

// 淡入动画
.chat-fade-enter-active,
.chat-fade-leave-active {
  transition: all 0.3s ease;
}

.chat-fade-enter-from,
.chat-fade-leave-to {
  opacity: 0;
  transform: scale(0.9);
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
